//index.js

import GT from '../../time'
import getFlatternDistance from '../../distance.js'
//获取应用实例
var app = getApp()
const getTimeX = GT.getTimeX
Page({
  data: {
    name: '',
    line: 0,
    time1: [],
    time2: [],
    transfer: false
  },
  //事件处理函数
  handleTap: function () {
    wx.navigateTo({
      url: '../list/list'
    })
  },
  onShow: function () {
    var that =this;
    var arr = [];
    // 获取当前位置
    wx.getLocation({
      type: 'wgs84',
      // 遍历data,
      success: function (res) {
        for (let i = 0; i < app.globalData.data.length; i++) {
          for (let j = 0; j < app.globalData.data[i].station.length; j++) {
            // 将坐标传入函数，返回distance
            let distance = Math.abs(getFlatternDistance(res.latitude, res.longitude, app.globalData.data[i].station[j].latitude, app.globalData.data[i].station[j].longitude))
            let a = {
              i: i,
              j: j,
              name: app.globalData.data[i].station[j].name,
              distance: distance,
              transfer: false
            }
            arr.push(a)
          }
        }
        // 对数组由小到大排序
        arr = arr.sort(function (x, y) {
          return x.distance - y.distance
        })
        app.globalData.nearest = arr[0]
        // 若arr[0].distance===arr[1].distance，说明该站点是换乘站
        if (arr[0].distance === arr[1].distance) {
          app.globalData.nearest.transfer = true;
        }
        that.setData({
          name: app.globalData.data[app.globalData.nearest.i].station[app.globalData.nearest.j].name,
          line: app.globalData.data[app.globalData.nearest.i].line,
          transfer: app.globalData.nearest.transfer
        })
        if (!app.globalData.nearest.transfer) {
          // 设置变量time1，time2
          that.setData({
            time1: getTimeX(app.globalData.data[app.globalData.nearest.i].station[app.globalData.nearest.j].timetable1),
            time2: getTimeX(app.globalData.data[app.globalData.nearest.i].station[app.globalData.nearest.j].timetable2)
          })
        } else {
          that.setData({
            // 若为换乘站，获取四个数组
            time1: getTimeX(app.globalData.data[app.globalData.nearest.i].station[app.globalData.nearest.j].timetable1),
            time2: getTimeX(app.globalData.data[app.globalData.nearest.i].station[app.globalData.nearest.j].timetable2),
            time3: getTimeX(app.globalData.data[app.globalData.nearest.i].station[app.globalData.nearest.j].timetable3),
            time4: getTimeX(app.globalData.data[app.globalData.nearest.i].station[app.globalData.nearest.j].timetable4)
          })
        }
      }
    })
  }
})

